package com.nmgs.config;

/**
 * 允许跨域请求
 *
 * @author Administrator
 */


import com.nmgs.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.*;
import java.io.PrintWriter;

@Component
@Slf4j
public class FilterConfig implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("request.getHeader(\"Origin\")=======>" + request.getHeader("Origin"));
/*        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));//支持跨域请求
        response.setHeader("Access-Control-Allow-Credentials", "true");//是否支持cookie跨域
        response.setHeader("Access-Control-Allow-Methods", "*");//X-forwared-port,X-forwarded-host,
        response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");//Origin, X-Requested-With, Content-Type, Accept,Access-Token
        String token = request.getHeader("token");*/
        /*if (token != null ) {
            return true;
        }
        if (request.getSession().getAttribute("token") == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            JSONObject res = new JSONObject();
            res.put("status", "-2");
            res.put("msg", "登录超时请重新登陆");
            PrintWriter out = null;
            out = response.getWriter();
            out.write(res.toString());
            out.flush();
            out.close();
            return false;
        }
        if (token != null) {
            try {
                boolean result = TokenUtil.verify(token, request);
                //判断绑定
                if (result) {
                    log.info("通过拦截器");
                    response.setHeader("token", TokenUtil.reToken(token, request));
                    return true;
                }
            } catch (Exception e) {
            }
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        JSONObject res = new JSONObject();
        res.put("status", "-1");
        res.put("msg", "鉴权失败");
        PrintWriter out = null;
        out = response.getWriter();
        out.write(res.toString());
        out.flush();
        out.close();*/
        return true;

    }
}